import json
import os
from typing import Optional

from motor.engine_server.utils.validators import FileValidator


def get_data_parallel_address() -> Optional[str]:
    file_path = os.getenv("RANK_TABLE_PATH")
    if not file_path:
        raise ValueError("Environment variable RANK_TABLE_PATH is not set")
    if not FileValidator(file_path) \
            .check_not_soft_link().check_file_size().check().is_valid():
        raise ValueError(f"{file_path} is not a valid file path.")
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            json_data = json.load(f)
    except FileNotFoundError:
        raise FileNotFoundError(f"File {file_path} not found")
    except json.JSONDecodeError:
        raise json.JSONDecodeError(f"File {file_path} is not valid JSON", doc="", pos=0)
    except Exception as e:
        raise RuntimeError(f"Error reading file: {str(e)}")

    for server in json_data.get("server_list", []):
        for device in server.get("device", []):
            if device.get("rank_id") == 0:
                return server.get("host_ip")

    raise ValueError("No device with rank_id=0 found")
